package com.fernandomdo.ServiceAdministrator;

// Android imports
import java.util.ArrayList;

import net.londatiga.android.ActionItem;
import net.londatiga.android.QuickAction;
import android.app.Activity;
import android.app.ListFragment;
import android.app.LoaderManager;
import android.content.Context;
import android.content.Loader;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.fernandomdo.ServiceAdministrator.Publisher.PublisherListItem;
import com.fernandomdo.ServiceAdministrator.databaseInterface.DatabaseInterface;
import com.fernandomdo.ServiceAdministrator.databaseInterface.DatabaseInterface.DatabaseConstants;


public class ListPublisherFragment extends ListFragment implements LoaderManager.LoaderCallbacks<Cursor> {
	private static final String TAG = "ListPublisherFragment";
	private static final int PUBLISHER = 1;
	private static final int ACTION_EDIT = 2;
	private static final int ACTION_DELETE = 3;
	
	private Context appContext;
	private PublisherListAdapter ListAdapter;
	private DataSetObserver dataObserver;
	private OnListItemSelectedListener itemSelectedListener;

	public static DatabaseInterface databaseInterface;
	
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		
		appContext = getActivity().getApplicationContext();
		databaseInterface = new DatabaseInterface(appContext);
		
		ListAdapter = new PublisherListAdapter(appContext, new ArrayList<PublisherListItem>());
	    dataObserver = new DataSetObserver() {
	    	@Override
	    	public void onChanged() {
	    		super.onChanged();
	    		setEmptyText(getResources().getString(R.string.list_empty));
	    	}
		};
		
		//territoryListAdapter.registerDataSetObserver(dataObserver);
	    setListAdapter(ListAdapter);
	    
	    // Initialize the loaders...
	    getLoaderManager().initLoader(PUBLISHER, null, this);
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		try {
			itemSelectedListener = (OnListItemSelectedListener) activity;
		}
		catch (ClassCastException e) {
			Log.e(TAG, "Bad Class", e);
			throw new ClassCastException(activity.toString() + "must implement OnListItemSelectedListener");
		}
	}
	
	@Override
	public void onPause() {
		super.onPause();
		ListAdapter.unregisterDataSetObserver(dataObserver);
		if(databaseInterface.readableDB != null) {
			databaseInterface.readableDB.close();
		}
		if(databaseInterface.writableDB != null){
			databaseInterface.writableDB.close();			
		}
	}
	
	@Override
	public void onResume() {
		super.onResume();
		ListAdapter.registerDataSetObserver(dataObserver);
		getLoaderManager().getLoader(PUBLISHER).forceLoad();
	}

	public interface OnListItemSelectedListener {
		/**
		 * The parent activity must implement this to share information with other fragments
		 * @param item
		 */
		public void onListItemSelected(Object item);	
	}
	
	
	
	@Override
	public void onListItemClick(ListView listView, View view, int pos, long id) {	
		Log.d(TAG, "onListItemClick");
		PublisherListItem item = (PublisherListItem)getListView().getItemAtPosition(pos);
		itemSelectedListener.onListItemSelected(item);
	}
	
	
	/**
	 * Called when the ListView that will hold the items has been created
	 * @param view
	 * @param savedInstanceState
	 */
	public void onViewCreated(View view, Bundle savedInstanceState) { 
						
		getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View listView, int pos, long id) {
				final PublisherListItem publisherItem = (PublisherListItem)getListView().getItemAtPosition(pos);
				Log.d(TAG, "item held down at pos: " + pos + " with id: " + publisherItem.id + " and name: " + publisherItem.name);
												
				QuickAction listActions;
				
			    listActions = new QuickAction(appContext);
			    		    
			    Drawable editIcon = appContext.getResources().getDrawable(R.drawable.ac_pencil);
			    Drawable deleteIcon = appContext.getResources().getDrawable(R.drawable.ac_trash);
			    
			    listActions.addActionItem(new ActionItem(ACTION_EDIT, getResources().getString(R.string.action_edit_territory), editIcon));
				listActions.addActionItem(new ActionItem(ACTION_DELETE, getResources().getString(R.string.action_delete_territory), deleteIcon));
				listActions.mAnimateTrack(false);
				listActions.setAnimStyle(QuickAction.ANIM_GROW_FROM_RIGHT);
				
				listActions.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {				
					@Override
					public void onItemClick(QuickAction source, int pos, int actionId) {
						//Bundle args;
						//SQLiteDatabase db;
						//Cursor rs;
						switch(actionId) {
						case ACTION_EDIT:	// Название
							//mDialogItemId = listActions.getId();
					  		//showDialog(DIALOG_CHANGE_NAME);
							break;
						case ACTION_DELETE:
							databaseInterface.deletePublisher(publisherItem.id);
							ListAdapter.notifyDataSetChanged();
							getLoaderManager().getLoader(PUBLISHER).forceLoad();
							break;
						default:						
							//mTerritoryForDelete = listActions.getId();
					  		
							break;
						}
					}
				});
				listActions.show(listView);
		    	return true;
			}
		}); 			
	}
	
		
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Async loaders to get the items from the database
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/**
	 * Simple Loader to retrieve the Publisher list
	 */
	static public class PublisherListLoader extends AsyncLoader<Cursor> {
		public PublisherListLoader(Context context) {
			super(context);
		}
		
		@Override
		public Cursor loadInBackground() {
			databaseInterface.readableDB = databaseInterface.databaseHelper.getReadableDatabase();
			Cursor cursor;
			final String[] FROM = { BaseColumns._ID, DatabaseConstants.PUBLISHER };
			final String ORDER_BY = DatabaseConstants.PUBLISHER;
			cursor =  databaseInterface.readableDB.query(DatabaseConstants.PUBLISHER_TABLE,  FROM, null, null, null, null, ORDER_BY);
			return cursor;
		}
	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle args) {
		Loader<Cursor> loader = null;
		if(id == PUBLISHER) {
			loader = new PublisherListLoader(appContext);		
		}
		return loader;
	}
	
	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		if(loader.getId() == PUBLISHER) {
			ArrayList<PublisherListItem> data = new ArrayList<PublisherListItem>();
			while(cursor.moveToNext()) {
				PublisherListItem item = new PublisherListItem();
				item.id = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
				item.name = cursor.getString(cursor.getColumnIndex(DatabaseConstants.PUBLISHER));
				data.add(item);
			}
			ListAdapter.swapData(data);
		}
		
		if(getListView().getCount() != 0) {
			itemSelectedListener.onListItemSelected(getListView().getItemAtPosition(0));			
		}
	}
	
	
	/**
	 * Make sure that you override this method when you create an instance of DatabaseInterface
	 */
	
	@Override
	public void onLoaderReset(Loader<Cursor> loader) {
		ListAdapter.swapData(new ArrayList<PublisherListItem>());
		Log.d(TAG, "onLoaderReset");
	}
}
